<template>
  <div class="mqtt-control">
    <!-- 连接控制 -->
    <div class="connection-control">
      <el-input 
        v-model="brokerUrl"
        placeholder="ws://broker-ip:port"
        style="width: 300px"
      >
        <template #prefix>
          <el-icon><Link /></el-icon>
        </template>
      </el-input>
      <el-button 
        @click="toggleConnection"
        :type="connected ? 'success' : 'primary'"
      >
        <el-icon><Link /></el-icon>
        {{ connected ? '断开连接' : '连接服务器' }}
      </el-button>
    </div>
 
    <!-- 状态栏 -->
    <div class="status-bar" :class="{ 'emergency': isEmergency }">
      <div class="status-indicator">
        <div class="led" :style="{ backgroundColor: statusColor }"></div>
        <span class="status-text">{{ statusText }}</span>
      </div>
      <div class="connection-status">
        <el-icon :color="connected ? '#67C23A' : '#909399'"><Connection /></el-icon>
        <span>{{ connectionStatus }}</span>
      </div>
    </div>
 
    <!-- 固定高度的日志框 -->
    <div class="log-container">
      <div class="log-header">
        <el-icon><Notebook /></el-icon>
        <span>系统日志</span>
      </div>
      <div class="log-content">
        <div 
          v-for="(log, index) in messageLog"
          :key="index"
          class="log-entry"
          :class="log.type" 
        >
          [{{ log.timestamp  }}] {{ log.content  }}
        </div>
      </div>
    </div>
 
  <!-- 灯光控制按钮 - 修改样式 -->
  <div class="button-group">
    <el-button 
      @click="sendCommand('ON')"
      :class="{'active-btn': currentStatus === 1, 'inactive-btn': currentStatus !== 1}"
      class="light-btn"
    >
      <el-icon><Light /></el-icon>
      开启场内灯光
    </el-button>
    <el-button
      @click="sendCommand('OFF')"
      :class="{'active-btn': currentStatus === 0, 'inactive-btn': currentStatus !== 0}"
      class="light-btn"
    >
      <el-icon><TurnOff /></el-icon>
      关闭场内灯光 
    </el-button>
  </div>
 
 
 <!-- 状态开关组 - 修改为单列 -->
 <div class="switch-group">
    <el-switch 
      v-model="emergencySwitch"
      active-text="ON"
      inactive-text="紧急警报"
      :style="{'--el-switch-on-color': '#F56C6C'}"
      :active-value="true"
      :inactive-value="false"
      @change="val => handleSwitchChange('R', val)"
    />
    <el-switch 
      v-model="temporarySwitch"
      active-text="ON"
      inactive-text="临时停工"
      :style="{'--el-switch-on-color': '#E6A23C'}"
      :active-value="true"
      :inactive-value="false"
      @change="val => handleSwitchChange('Y', val)"
    />
    <el-switch
      v-model="normalSwitch"
      active-text="ON"
      inactive-text="正常通勤"
      :style="{'--el-switch-on-color': '#67C23A'}"
      :active-value="true"
      :inactive-value="false"
      @change="val => handleSwitchChange('G', val)"
    />
  </div>


  </div>
</template>
 
<script>
import { 
  Connection, Link, Lightning, TurnOff, 
  Warning, Check, Notebook 
} from '@element-plus/icons-vue'
import mqtt from 'mqtt/dist/mqtt.min' 
 
export default {
  components: {
    Connection, Link, Light: Lightning, TurnOff, 
    Warning, Check, Notebook 
  },
  data() {
    return {
      brokerUrl: "ws://192.168.80.151:8083/mqtt",
      client: null,
      connected: false,
      currentStatus: 0,
      isEmergency: false,
      messageLog: [],
      emergencySwitch: false,
      temporarySwitch: false,
      normalSwitch: true 
    }
  },
  computed: {
    connectionStatus() {
      return this.connected  ? `已连接 ${this.brokerUrl}`  : '未连接'
    },
    statusText() {
      return this.isEmergency  ? '紧急状态' : 
        ['设备关闭', '灯光开启', '紧急警报', '临时停工', '正常通勤'][this.currentStatus]
    },
    statusColor() {
      return this.isEmergency  ? '#FF0000' : 
        ['#888', '#4CAF50', '#F56C6C', '#E6A23C', '#67C23A'][this.currentStatus]
    }
  },
  methods: {
    toggleConnection() {
      if (this.connected)  {
        this.disconnect() 
      } else {
        this.connect() 
      }
    },
    connect() {
      this.client  = mqtt.connect(this.brokerUrl,  {
        clientId: `client-${Date.now()}`, 
        clean: true,
        connectTimeout: 5000 
      })
 
      this.client.on('connect',  () => {
        this.connected  = true
        this.logMessage('MQTT 连接成功', 'info')
        this.client.subscribe('factory/status',  { qos: 1 }, (err) => {
          if (!err) this.logMessage(' 已订阅状态主题', 'info')
        })
      })
 
      this.client.on('message',  (topic, message) => {
        const msg = message.toString() 
        this.logMessage(` 收到消息 [${topic}]: ${msg}`, 'data')
        
        if (topic === 'factory/status') {
          if (msg.includes('"light":1'))  {
            this.currentStatus  = 1
            this.updateSwitches(1) 
          } else if (msg.includes('"light":0'))  {
            this.currentStatus  = 0
            this.updateSwitches(0) 
          } else if (msg.includes('"light":2'))  {
            this.currentStatus  = 2
            this.updateSwitches(2) 
          } else if (msg.includes('"light":3'))  {
            this.currentStatus  = 3
            this.updateSwitches(3) 
          } else if (msg.includes('"light":4'))  {
            this.currentStatus  = 4
            this.updateSwitches(4) 
          }
        }
      })
 
      this.client.on('error',  (err) => {
        this.logMessage(` 连接错误: ${err}`, 'error')
        this.connected  = false
      })
    },
    disconnect() {
      if (this.client)  {
        this.client.end() 
        this.client  = null
        this.connected  = false 
        this.logMessage(' 已断开连接', 'warning')
      }
    },
    sendCommand(command) {
      if (!this.connected)  {
        this.logMessage(" 请先连接服务器", 'warning')
        return 
      }
      
      this.client.publish('factory/control',  command, { qos: 1 }, (err) => {
        if (!err) {
          this.logMessage(` 指令发送: ${command}`, 'command')
        } else {
          this.logMessage(` 发送失败: ${err}`, 'error')
        }
      })
    },
    handleSwitchChange(command, isActive) {
      if (isActive) {
        // 互斥逻辑 
        if (command === 'R') {
          this.temporarySwitch  = false 
          this.normalSwitch  = false 
        } else if (command === 'Y') {
          this.emergencySwitch  = false 
          this.normalSwitch  = false 
        } else if (command === 'G') {
          this.emergencySwitch  = false 
          this.temporarySwitch  = false 
        }
        this.sendCommand(command) 
      }
    },
    updateSwitches(status) {
      this.emergencySwitch  = (status === 2)
      this.temporarySwitch  = (status === 3)
      this.normalSwitch  = (status === 4)
      this.isEmergency  = (status === 2 )
    },
    logMessage(content, type = 'info') {
      this.messageLog.unshift({ 
        timestamp: new Date().toLocaleTimeString(),
        content,
        type
      })
      if (this.messageLog.length  > 100) this.messageLog.pop() 
    }
  },
  beforeUnmount() {
    this.disconnect() 
  }
}
</script>
 
<style scoped>
.mqtt-control {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}
 
/* 连接控制 */
.connection-control {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}
 
/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 15px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  border-left: 4px solid #4CAF50;
}
 
.status-bar.emergency  {
  border-left-color: #F56C6C;
  background-color: #fef0f0;
}
 
.status-indicator {
  display: flex;
  align-items: center;
  gap: 10px;
}
 
.led {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  box-shadow: 0 0 5px currentColor;
}
 
.status-text {
  font-weight: bold;
}
 
.connection-status {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}
 
/* 日志容器 */
.log-container {
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 15px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
 
.log-header {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
}
 
.log-content {
  height: 200px;
  overflow-y: auto;
  padding: 10px;
  font-family: monospace;
  font-size: 13px;
}
 
.log-entry {
  padding: 6px 0;
  border-bottom: 1px solid #f5f5f5;
}
 
.log-entry:last-child {
  border-bottom: none;
}
 
.log-entry.error  {
  color: #F56C6C;
}
 
.log-entry.command  {
  color: #409EFF;
}
 
.log-entry.info  {
  color: #909399;
}
 





/* 按钮组 */
/* 按钮组 */
.button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}
 
.light-btn {
  flex: 1;
  height: 48px;
  font-size: 16px;
  transition: all 0.3s;
  border-width: 1px;
  border-style: solid;
}
 
/* 选中状态按钮 - 使用悬停样式 */
.light-btn.el-button--primary  {
  background-color: #ecf5ff;  /* 浅蓝色背景 */
  border-color: #c6e2ff;     /* 浅蓝色边框 */
  color: #409eff;            /* 蓝色文字 */
}
 
/* 未选中状态按钮 */
.light-btn:not(.el-button--primary) {
  background-color: #f5f7fa;  /* 浅灰色背景 */
  border-color: #dcdfe6;      /* 浅灰色边框 */
  color: #606266;             /* 灰色文字 */
}
 
/* 悬停效果 - 比选中状态稍深 */
.light-btn:hover {
  background-color: #d9ecff;
  border-color: #b3d8ff;
  color: #409eff;
}
 
/* 确保选中状态的悬停效果 */
.light-btn.el-button--primary:hover  {
  background-color: #d9ecff;
  border-color: #b3d8ff;
  color: #409eff;
}
 






/* 开关组 */
.switch-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  background-color: #f8f8f8;
  padding: 20px;
  border-radius: 4px;
}
 
.switch-item {
  display: flex;
  align-items: center;
}
 
.switch-item .el-switch {
  flex: 1;
}
 
.switch-item .el-switch__text {
  font-size: 14px;
  margin: 0 10px;
}
</style>